import hashlib
import os


# 生成字符串的MD5值
def str2md5(content=None):
    if not content:
        return ''
    md5gen = hashlib.md5()
    md5gen.update(content.encode())
    return md5gen.hexdigest()


# 生成字符串的SHA256值
def str2sha256(content=None):
    if not content:
        return ''
    sha256gen = hashlib.sha256()
    sha256gen.update(content.encode())
    return sha256gen.hexdigest()


# 生成文件的MD5值
def file2md5(filename):
    hash_value = ''
    if os.path.exists(filename):
        try:
            md5obj = hashlib.md5()
            with open(filename, 'rb') as f:
                md5obj.update(f.read())
            hash_value = md5obj.hexdigest()
        except Exception as e:
            print(e)
    return hash_value


def file2sha256(filename):
    hash_value = ''
    if os.path.exists(filename):
        try:
            sha256obj = hashlib.sha256()
            with open(filename, "rb") as f:
                sha256obj.update(f.read())
            hash_value = sha256obj.hexdigest()
        except Exception as e:
            print(e)
    return hash_value


def file2sha1(filename):
    hash_value = ''
    if os.path.exists(filename):
        try:
            sha1obj = hashlib.sha1()
            with open(filename, 'rb') as f:
                sha1obj.update(f.read())
            hash_value = sha1obj.hexdigest()
        except Exception as e:
            print(e)
    return hash_value


def file2sha3(filename):
    hash_value = ''
    if os.path.exists(filename):
        try:
            sha3obj = hashlib.sha3_384()
            with open(filename, 'rb') as f:
                sha3obj.update(f.read())
            hash_value = sha3obj.hexdigest()
        except Exception as e:
            print(e)
    return hash_value

